﻿using BussinessLogicLayer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TestingSystem.Common;

namespace TestingSystem.TestingManager
{
    public partial class TestingAddEditForm : Form
    {
        private string test_ID = "";
        private DateTime testCreationDate = DateTime.Today;
        public bool Refresh { get; set; }
        public TEST TestUpdated { get; set; }
        private BindingList<TestSection> Sections = new BindingList<TestSection>();

        public TestingAddEditForm(string test_ID)
        {
            InitializeComponent();
            this.test_ID = test_ID;
        }

        private void TestingAddEditForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Load and binding list courses to course combobox
                this.cboCourse.DataSource = this.GetCourses();
                this.cboCourse.SelectedIndex = -1;

                // Load and binding list users to user combobox
                this.cboLecture.DataSource = this.GetUsers();
                this.cboLecture.SelectedIndex = -1;

                this.dgvSections.DataSource = Sections;

                // Edit testing
                if (!string.IsNullOrWhiteSpace(this.test_ID))
                {
                    try
                    {
                        // Load testing info
                        var test = BLL_Test.Get(this.test_ID);
                        this.cboCourse.SelectedValue = test.COURSE_ID;
                        this.cboLecture.SelectedValue = test.USER_ID;
                        this.txtDesc.Text = test.TEST_DESC;
                        this.dtpStarttime.Value = test.TEST_START_TIME;
                        this.npdDuration.Value = test.TEST_DURATION;
                        this.testCreationDate = test.TEST_CREATION_DATE;

                        var list = BLL_Test_Section.Get(new TEST { TEST_ID = this.test_ID });
                        foreach (var item in list)
                        {
                            this.Sections.Add(new TestSection
                            {
                                Test_Section_ID = item.TEST_SECTION_ID,
                                Test_Section_Desc = item.TEST_SECTION_DESC.Trim(),
                                Num_Question = item.NUM_QUESTION
                            });
                        }

                        this.dgvSections.Columns["Test_Section_ID"].Visible = true;
                        this.dgvSections.Columns["Test_Section_Desc"].Width = 320;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("The error occured when process connect to database. Please try again.", "Error", MessageBoxButtons.OK);
                    }
                }
            }
            catch (Exception ex)
            {
                // Show error message
                MessageBox.Show("The error occured when processing. Please try again.", "Error", MessageBoxButtons.OK);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.cboCourse.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a course.", "Alert", MessageBoxButtons.OK);
                return;
            }

            if (this.cboLecture.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a lecture.", "Alert", MessageBoxButtons.OK);
                return;
            }

            //if (dtpStarttime.Value < DateTime.Now)
            //{
            //    MessageBox.Show("Start time must be greater than today.", "Alert", MessageBoxButtons.OK);
            //    return;
            //}

            try
            {
                bool result = false;
                var test = new TEST
                    {
                        USER_ID = this.cboLecture.SelectedValue.ToString(),
                        COURSE_ID = this.cboCourse.SelectedValue.ToString(),
                        TEST_DESC = this.txtDesc.Text.Trim(),
                        TEST_START_TIME = this.dtpStarttime.Value,
                        TEST_DURATION = (int)this.npdDuration.Value
                    };

                if (string.IsNullOrWhiteSpace(this.test_ID))
                {
                    test.TEST_CREATION_DATE = DateTime.Today;
                    test.TEST_SECTIONS = new List<TEST_SECTION>();
                    foreach (var section in Sections)
                    {
                        var test_Section = new TEST_SECTION();
                        test_Section.TEST_SECTION_DESC = section.Test_Section_Desc;
                        test_Section.TEST_SECTION_ITEMS = new List<TEST_SECTION_ITEM>();
                        foreach (var item in section.Questions)
                        {
                            var test_section_item = new TEST_SECTION_ITEM();
                            test_section_item.QUESTION_ID = item.Question_ID;
                            test_Section.TEST_SECTION_ITEMS.Add(test_section_item);
                        }
                        test.TEST_SECTIONS.Add(test_Section);
                    }
                    result = BLL_Test.Insert(test);
                    this.Refresh = true;
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    test.TEST_ID = this.test_ID;
                    test.TEST_CREATION_DATE = this.testCreationDate;
                    test.TEST_SECTIONS = new List<TEST_SECTION>();
                    
                    foreach (var section in Sections)
                    {
                        var test_Section = new TEST_SECTION();
                        test_Section.TEST_SECTION_ID = section.Test_Section_ID;
                        test_Section.TEST_ID = Convert.ToDecimal(this.test_ID);
                        test_Section.TEST_SECTION_DESC = section.Test_Section_Desc;
                        test_Section.TEST_SECTION_ITEMS = new List<TEST_SECTION_ITEM>();
                        foreach (var item in section.Questions)
                        {
                            var test_section_item = new TEST_SECTION_ITEM();
                            test_section_item.QUESTION_ID = item.Question_ID;
                            test_Section.TEST_SECTION_ITEMS.Add(test_section_item);
                        }
                        test.TEST_SECTIONS.Add(test_Section);
                    }
                    result = BLL_Test.Update(test);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;

                    this.Refresh = true;
                    this.TestUpdated = new TEST
                        {
                            USER_ID = test.TEST_ID,
                            COURSE_ID = test.COURSE_ID,
                            TEST_DESC = test.TEST_DESC,
                            TEST_START_TIME = test.TEST_START_TIME,
                            TEST_CREATION_DATE = test.TEST_CREATION_DATE,
                            TEST_DURATION = test.TEST_DURATION
                        };
                }

                if (result)
                {
                    MessageBox.Show("Save successfull.", "Save", MessageBoxButtons.OK);
                    
                    // Close form after update success
                    this.Close();
                }
                else
                {
                    MessageBox.Show("The error occured to save to database. Please try again.", "Error", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                // Show error message
                MessageBox.Show("The error occured to save to database. Please try again.", "Error", MessageBoxButtons.OK);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnNewSection_Click(object sender, EventArgs e)
        {
            // Show form add edit section
            AddEditTestSectionForm form = new AddEditTestSectionForm(-1, null);
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.Sections.Add(form.Section);
            }
        }

        private void btnEditSection_Click(object sender, EventArgs e)
        {
            // Show form add edit section
            if (this.dgvSections.SelectedRows.Count > 0)
            {
                AddEditTestSectionForm form = new AddEditTestSectionForm((dgvSections.SelectedRows[0].DataBoundItem as TestSection).Test_Section_ID, (dgvSections.SelectedRows[0].DataBoundItem as TestSection));
                if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var pos = this.Sections.IndexOf(dgvSections.SelectedRows[0].DataBoundItem as TestSection);
                    if (pos > -1)
                    {
                        this.Sections[pos] = form.Section;
                    }
                }
            }
        }

        private void btnDeleteSection_Click(object sender, EventArgs e)
        {
            if (this.dgvSections.SelectedRows.Count > 0)
            {
                this.Sections.Remove(dgvSections.SelectedRows[0].DataBoundItem as TestSection);
            }
        }

        private void dgvSections_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dgvSections.SelectedRows.Count > 0)
            {
                btnEditSection.Enabled = true;
                btnDeleteSection.Enabled = true;
            }
            else
            {
                btnEditSection.Enabled = false;
                btnDeleteSection.Enabled = false;
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (this.cboCourse.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a course.", "Alert", MessageBoxButtons.OK);
                return;
            }

            if (this.cboLecture.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a lecture.", "Alert", MessageBoxButtons.OK);
                return;
            }

            var test = new TEST
            {
                USER_ID = this.cboLecture.SelectedValue.ToString(),
                COURSE_ID = this.cboCourse.SelectedValue.ToString(),
                TEST_DESC = this.txtDesc.Text.Trim(),
                TEST_START_TIME = this.dtpStarttime.Value,
                TEST_DURATION = (int)this.npdDuration.Value
            };

            test.TEST_SECTIONS = new List<TEST_SECTION>();
            foreach (var section in Sections)
            {
                var test_Section = new TEST_SECTION();
                test_Section.TEST_SECTION_ID = section.Test_Section_ID;
                if (!string.IsNullOrWhiteSpace(this.test_ID))
                {
                    test_Section.TEST_ID = Convert.ToDecimal(this.test_ID);
                }
                test_Section.TEST_SECTION_DESC = section.Test_Section_Desc;
                test_Section.TEST_SECTION_ITEMS = new List<TEST_SECTION_ITEM>();

                if (section.Test_Section_ID == -1)
                {
                    foreach (var item in section.Questions)
                    {
                        var test_section_item = new TEST_SECTION_ITEM();
                        test_section_item.QUESTION_ID = item.Question_ID;
                        test_Section.TEST_SECTION_ITEMS.Add(test_section_item);
                    }
                }
                else
                {
                    for (int i = 0; i < section.Questions.Count; i++)
                    {
                        var test_section_item = new TEST_SECTION_ITEM();
                        test_section_item.QUESTION_ID = section.Questions[i].Question_ID;
                        test_Section.TEST_SECTION_ITEMS.Add(test_section_item);
                    }
                }
                test.TEST_SECTIONS.Add(test_Section);
            }

            Preview form = new Preview(test);
            form.ShowDialog();
        }

        #region Helper Methods

        private List<Course> GetCourses()
        {
            var listCourse = new List<Course>();

            try
            {
                var listDTOCourse = BLL_Course.LoadAll();
                foreach (var item in listDTOCourse)
                {
                    listCourse.Add(new Course(item.COURSE_ID, item.COURSE_NAME));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return listCourse;
        }

        private List<User> GetUsers()
        {
            var listUser = new List<User>();

            try
            {
                var listDTOUser = BLL_User.LoadAll();
                foreach (var item in listDTOUser)
                {
                    listUser.Add(new User(item.USER_ID, item.USER_LAST_NAME + ", " + item.USER_FIRST_NAME));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return listUser;
        }

        #endregion
    }
}
